<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="项目职责" prop="role">
        <el-select v-model="dataForm.role" placeholder="请选择合作者职责">
          <el-option v-for="item in state.roleText" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="合作者" prop="partcipantIds">
        <el-input placeholder="请选择" v-model="dataForm.usernameString" @click="addUser"></el-input>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}邀请</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="state.addUserVisible" title="用户" :close-on-click-modal="false" :close-on-press-escape="false">
    <Dept :placeholder="$t('dept.title')" v-model="dataForm.deptName" @userForm="userForm" :projectId="props.projectId"
      :userpage="state.userpage" :userlimit="state.userlimit" :totalUser="state.totalUser" :role="dataForm.role"></Dept>
    <br />
    <el-table v-loading="state.dataListLoading" ref="dataUserListRef" :data="state.dataUserForm" border
      @selection-change="dataListSelectionChange" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="username" :label="$t('user.username')" sortable="custom" header-align="center"
        align="center"></el-table-column>
      <el-table-column prop="deptName" :label="$t('user.deptName')" header-align="center"
        align="center"></el-table-column>
      <el-table-column prop="status" :label="$t('user.status')" sortable="custom" header-align="center" align="center">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status === 0" size="small" type="danger">{{ $t("user.status0") }}</el-tag>
          <el-tag v-else size="small" type="success">{{ $t("user.status1") }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <template v-slot:footer>
      <el-button @click="state.addUserVisible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormUserSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
    <el-pagination :current-page="state.userpage" :page-sizes="[10, 20, 50, 100]" :page-size="state.userlimit"
      :total="state.totalUser" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeUserHandle"
      @current-change="pageCurrentChangeUserHandle"> </el-pagination>
  </el-dialog>
</template>

<script lang="ts" setup>
import useView from "@/hooks/useView";
import { reactive, ref, toRefs } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import Dept from "./ren-dept-tree.vue";
import { IObject } from "@/types/interface";
import { useAppStore } from "@/store";
import { ElMessage, ElNotification } from "element-plus";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const store = useAppStore();

const props = defineProps({
  projectId: String
});
const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "" as string,
  participantIds: [] as any[],
  projectId: "" as any,
  role: 1,
  createDate: "",
  creator: "",
  updateDate: "",
  updater: "",
  deptName: "",
  // userId: [],
  username: [] as any[],
  usernameString: ""
});
const view = reactive({
  roleText: [
    // {value:0,label:"项目创建者"},
    { value: 1, label: "项目负责人" },
    { value: 2, label: "项目成员" },
    { value: 3, label: "项目联系人" }
  ],
  addUserVisible: false,
  getDataListIsPage: true,
  totalUser: 0,
  userpage: 1,
  userlimit: 10,
  dataUserForm: [],
  projectName: ""
});

const state = reactive({ ...useView(view), ...toRefs(view) });

const rules = ref({});
const sysNotice = reactive({
  id: "",
  noticeType: 3,
  title: "项目通知",
  content: ` ${store.state.user.username} 邀请您成为《${state.projectName}》的 ${dataForm.role === 1 ? "项目负责人" : dataForm.role === 2 ? "项目成员" : "项目联系人"} 。`,
  receiverType: 0,
  receiverTypeIds: "",
  receiverTypeList: [],
  status: 0,
  senderName: "",
  senderDate: "",
  creator: 0,
  createDate: ""
});
const email = reactive({
  id: "1685219987920257026",
  emails: [] as any,
  mailTo: "",
  mailCc: "",
  params: `{'senderName':'${store.state.user.username}','projectName': '${state.projectName}','role': '${dataForm.role === 1 ? "项目负责人" : dataForm.role === 2 ? "项目成员" : "项目联系人"}'}`
});
const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";
  console.log(store.state.user.username);
  baseService.get("/poap/poapparticipantproject/selectProjectName", { projectId: props.projectId }).then((res) => {
    console.log(res);
    if (res.code != 0) return false;
    state.projectName = res.data;
  });

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/poap/poapparticipantproject/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

const addUser = () => {
  state.addUserVisible = true;
  dataForm.participantIds = [];
  dataForm.usernameString = "";
  queryUser();
};
const queryUser = () => {
  // dataForm.projectId = props.projectId;
  // console.log("add")
  // console.log(dataForm)
  // baseService.get("poap/poapproject/selectUser",{
  //   page: state.getDataListIsPage ? state.userpage : null,
  //   limit: state.getDataListIsPage ? state.userlimit : null,
  //   role: dataForm.role,
  //   deptName: dataForm.deptName,
  //   projectId: props.projectId
  // }).then( res => {
  //   if(res.code !== 0) return false;
  //   state.dataUserForm = res.data.list;
  //   state.totalUser = res.data.total;
  // })
};
const dataUserListRef = ref();

const dataListSelectionChange = (val: any) => {
  console.log(val);
  for (let i = 0; i < val.length; i++) {
    dataForm.participantIds[i] = val[i].id;
    dataForm.username[i] = val[i].username;
  }
};

const userForm = (val: IObject) => {
  console.log(val);
  state.dataUserForm = val.userList;
  state.totalUser = val.total;
  console.log(state.dataUserForm);
};
const pageSizeChangeUserHandle = (val: number) => {
  state.userpage = 1;
  state.userlimit = val;
  queryUser();
};
const pageCurrentChangeUserHandle = (val: number) => {
  state.userpage = val;
  queryUser();
};
const dataFormUserSubmitHandle = () => {
  // console.log(dataForm)
  // baseService.get("poap/poapproject/selectCreatorStatus", {
  //   projectId:props.projectId,
  //   role:dataForm.role
  // }).then(res =>{
  //   console.log(res);
  //   if(res.data == "1" && dataForm.role == 0) {
  //   // if(res.code != 0) {
  //     ElMessage.error('项目创建者已存在，请勿重复添加')
  //     state.addUserVisible = false;
  //     visible.value=false;
  //     return false;
  //   }
  //
  // }).catch(res => {
  //   console.log(res)
  // })
  state.addUserVisible = false;
  for (let i = 0; i < dataForm.username.length - 1; i++) {
    dataForm.usernameString = dataForm.username[i] + "，";
  }
  dataForm.usernameString = dataForm.usernameString + dataForm.username[dataForm.username.length - 1];
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataForm.projectId = props.projectId;
  console.log(dataForm);
  // dataFormRef.value.validate((valid: boolean) => {
  //   if (!valid) {
  //     return false;
  //   }
  //   (!dataForm.id ? baseService.post : baseService.put)("/poap/poapparticipantproject", dataForm).then((res) => {
  //     ElMessage.success({
  //       message: t("prompt.success"),
  //       duration: 500,
  //       onClose: () => {
  //         visible.value = false;
  //         emit("refreshDataList");
  //       }
  //     });
  //   });
  // });

  // if(!dataForm.id){
  email.params = `{"senderName":"${store.state.user.username}","projectName": "${state.projectName}","role": "${dataForm.role === 1 ? "项目负责人" : dataForm.role === 2 ? "项目成员" : "项目联系人"}"}`;
  console.log(email);
  console.log(dataForm.participantIds);
  baseService.post("/message/mailtemplate/sendGroup", { templateId: email.id, ids: dataForm.participantIds, params: email.params }).then((res) => {
    console.log(res);
    if (res.code != 0) return false;
    // email.emails=res.data
    // let i=0;
    // while (i<email.emails.length){
    //   email.mailTo=email.emails[i];
    //   baseService
    //     .post("/message/mailtemplate/send", dataForm, {
    //       "content-type": "application/x-www-form-urlencoded"
    //     })
    //     .then((res) => {
    //       ElMessage.success({
    //         message: t("prompt.success"),
    //         duration: 500,
    //         onClose: () => {
    //           visible.value = false;
    //           emit("refreshDataList");
    //         }
    //       });
    //     });
    //   setInterval(()=>{
    //     i++;
    //   },60000);
    // }
  });
  ElNotification({
    type: "info",
    message: "邀请成功，稍后发送邮件😊"
  });
  sysNotice.senderName = store.state.user.username;
  sysNotice.content = `${store.state.user.username} 邀请您成为“${state.projectName}”的  ${dataForm.role === 1 ? "项目负责人" : dataForm.role === 2 ? "项目成员" : "项目联系人"} 。`;

  console.log(sysNotice);
  console.log(dataForm.participantIds);
  baseService.post("/poap/poapparticipantproject/invite", { noticeDTO: sysNotice, participantIds: dataForm.participantIds }).then((res) => {
    console.log(res);
    if (res.code != 0) return false;
    ElMessage.success({
      message: "通知已发送",
      duration: 500,
      onClose: () => {
        visible.value = false;
        emit("refreshDataList");
      }
    });
  });
};

defineExpose({
  init
});
</script>
